import asyncio
import random
import cv2
import os
import numpy as np
import base64
from pyppeteer import launch
from pyzbar.pyzbar import decode
from PIL import Image
def find_gap_position(bg_img, slider_img):
    bg_edge = cv2.Canny(bg_img, 100, 200)
    slider_edge = cv2.Canny(slider_img, 100, 200)
    
    result = cv2.matchTemplate(bg_edge, slider_edge, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    gap_position = max_loc[0] if max_loc[0]!=0 else max_loc[1]
    return gap_position
async def login():
    # 启动浏览器
    browser = await launch(
        headless=False,
        args=['--window-size=1920,1080'],
        ignoreDefaultArgs=['--enable-automation'],
        userDataDir= os.path.expanduser(r'~\AppData\Local\Google\Chrome\User Data'),
        executablePath=r'C:\Program Files\GptChrome\GptBrowser.exe'
    )
    page = await browser.newPage()
    await page.setViewport({'width': 1920, 'height': 1080})

    try:
        await page.setExtraHTTPHeaders({
            'Accept-Language': 'en-US,en;q=0.9',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'
        })
        await page.goto('https://www.test.com',timeout=90000)

        await page.waitForSelector('.header-users>.login')
        await page.click('.header-users>.login')
        await asyncio.sleep(0.5)

        await page.waitForSelector('.el-input__inner')
        await asyncio.sleep(0.5)
        btn = await page.xpath('//input[@class="el-input__inner"]')

        if(len(btn)>1):
            await btn[0].type('411381198910184530')
            await btn[1].type('Asxuyou12')
        
            await page.waitForSelector('.el-button')
            await page.click('.el-button')
            await asyncio.sleep(0.5)

            img_bg = await page.waitForSelector('#tianai-captcha-slider-bg-img')
            img_bg_rt = await img_bg.boundingBox()
            img_src = await page.evaluate('(element) => element.src', img_bg)
            img_src = np.frombuffer(base64.b64decode(img_src[img_src.find('base64,')+7:]), dtype=np.uint8)
            img_src = cv2.imdecode(img_src, cv2.IMREAD_GRAYSCALE)
            img_src = cv2.resize(img_src,(int(img_bg_rt['width']),int(img_bg_rt['height'])))
            print(img_src.shape)

            img_fg = await page.waitForSelector('#tianai-captcha-slider-move-img')
            img_fg_rt = await img_fg.boundingBox()
            img_move = await page.evaluate('(element) => element.src', img_fg)
            img_move = np.frombuffer(base64.b64decode(img_move[img_move.find('base64,')+7:]), dtype=np.uint8)
            img_move = cv2.imdecode(img_move, cv2.IMREAD_GRAYSCALE)
            img_move = cv2.resize(img_move,(int(img_fg_rt['width']),int(img_fg_rt['height'])))
            print(img_move.shape)

            distance = find_gap_position(img_src,img_move)
            print('distance:',distance)

            slider = await page.waitForSelector('.slider-move-btn')
            await asyncio.sleep(0.5)
            box = await slider.boundingBox()
            slider_x = box['x']+ box['width'] / 2
            slider_y = box['y']+ box['height'] / 2

            await page.mouse.move(slider_x, slider_y)
            await asyncio.sleep(0.1 + random.random() * 0.2)
            print('move:',slider_x,slider_y,box)
            
            await page.mouse.down()
            await page.mouse.move(slider_x+distance+ random.randint(-3, 3), slider_y+ random.randint(-3, 3),{'steps':20})
            await asyncio.sleep(0.1 + random.random() * 0.2)
            await page.mouse.up()
            await asyncio.sleep(1)
        
        await asyncio.sleep(1)
        # btn = await page.xpath('//div[@id="specialBox"]//a')
        # btn_ref = await page.evaluate('(element) => element.href', btn[8])
        await page.goto('https://www.test.com')
        await asyncio.sleep(1)
        
        try:
            img_code = await page.waitForSelector('#qrcode img')
        except Exception as e:
            await page.waitForSelector('main',timeout=10)
            await page.waitForSelector('.el-button')
            await page.click('.el-button')
            img_code = await page.waitForSelector('.cursor-pointer img')
        except Exception as e:
            await page.waitForSelector('.mineLeftBox menuItem:nth-of-type(2)')
            await page.click('.mineLeftBox menuItem:nth-of-type(2)')
            img_code = await page.waitForSelector('#qrcode img')
        except Exception as e:
            print(e)

        await page.waitForSelector('.el-dialog__footer .el-button')
        await page.click('.el-dialog__footer .el-button')
        await asyncio.sleep(0.5)

        img_code = await page.evaluate('(element) => element.src', img_code)
        img_code = np.frombuffer(base64.b64decode(img_code[img_code.find('base64,')+7:]), dtype=np.uint8)
        img_code = cv2.imdecode(img_code, cv2.IMREAD_GRAYSCALE)
        qr_detector = cv2.QRCodeDetector()
        retval, decoded_info, points, straight_qrcode = qr_detector.detectAndDecodeMulti(img_code)
        if retval:
            for i in range(len(decoded_info)):
                data = decoded_info[i]
                print(data)
        else:
            data = decode(img_code)
            print(data)
        await asyncio.sleep(300000)
    except Exception as e:
        print(e)
    finally:
        # 关闭浏览器
        await browser.close()

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(login())